<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta content="IE=edge" http-equiv="X-UA-Compatible">
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <title>Document</title>
    <!-- 引入样式 -->
    <link href="../../plugins/element-ui/index.css" rel="stylesheet"/>
    <link href="../../styles/common.css" rel="stylesheet"/>
    <link href="../../styles/page.css" rel="stylesheet"/>
</head>
<body style="position: relative">
<div class="dashboard-container" id="category-app">
    <div class="container">
        <div
                class="tableBar"
                style="display: inline-block"
        >
            <el-button
                    @click="addClass('class')"
                    class="continue"
                    type="primary"
            >
                + 新增部门
            </el-button>

            <el-button
                    @click="exportExcel()"
                    plain
                    type="success"
            >
                <i class="el-icon-download el-icon--left"></i>
                导出数据
            </el-button>
        </div>
        <el-upload
                :accept="'.xls,.xlsx'"
                :before-remove="beforeRemove"
                :limit="3"
                :name="'file'"
                :on-error="importError"
                :on-success="importSuccess"
                action="http://localhost:8081/department/importExcel"
                auto-upload="true"
                show-file-list="true"
                style="margin-bottom: 10px"
        >

            <el-button plain
                       size="small"
                       slot="trigger"
                       type="success"
            >
                <i class="el-icon-upload2 el-icon--left"></i>
                导入数据
            </el-button>
        </el-upload>
        <el-table
                :data="tableData"
                class="tableBox"
                stripe
        >
            <el-table-column
                    label="部门编号"
                    prop="did"
            />
            </el-table-column>

            <el-table-column
                    label="部门名称"
                    prop="dname"
            ></el-table-column>
            <el-table-column
                    label="部门人数"
                    prop="num"
            />
            </el-table-column>

            <el-table-column
                    label="备注"
                    prop="detail"
            />
            </el-table-column>


            <el-table-column
                    align="center"
                    label="操作"
                    width="160"
            >
                <template slot-scope="scope">
                    <el-button
                            @click="editHandle(scope.row)"
                            class="blueBug"
                            size="small"
                            type="text"
                    >
                        修改
                    </el-button>
                    <el-button
                            @click="deleteHandle(scope.row)"
                            class="delBut non"
                            size="small"
                            type="text"
                    >
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
                :page-size="pageSize"
                :page-sizes="[3, 5, 10, 15]"
                :total="counts"
                @current-change="handleCurrentChange"
                @size-change="handleSizeChange"
                class="pageList"
                layout="total, sizes, prev, pager, next, jumper"
        ></el-pagination>
    </div>
    <!--    柱状图容器-->
    <div id="container2" style="height: 400px"></div>
    <!--    饼状图容器-->
    <div id="container3" style="height: 600px"></div>


    <!--    添加分类弹窗-->
    <el-dialog
            :before-close="handleClose"
            :title="classData.title"
            :visible.sync="classData.dialogVisible"
            width="30%"
    >
        <el-form
                class="demo-form-inline"
                label-width="100px"
        >
            <el-form-item label="部门编号：" v-if="action==='add'">
                <el-input
                        maxlength="14"
                        placeholder="请输入编号"
                        v-model="classData.dId"
                />
            </el-form-item>
            <el-form-item label="部门名称：">
                <el-input placeholder="请输入名称" v-model="classData.dName"/>
            </el-form-item>

            <el-form-item label="备注：">
                <el-input
                        maxlength="14"
                        placeholder="请输入备注"
                        v-model="classData.detail"
                />
            </el-form-item>
        </el-form>
        <span
                class="dialog-footer"
                slot="footer"
        >
        <el-button
                @click="classData.dialogVisible = false"
                size="medium"
        >取 消</el-button>
        <el-button
                @click="submitForm()"
                size="medium"
                type="primary"
        >确 定</el-button>
        <el-button
                @click="submitForm('go')"
                class="continue"
                size="medium"
                type="primary"
                v-if="action != 'edit'"
        > 保存并继续添加 </el-button>
      </span>
    </el-dialog>


</div>
<!-- 开发环境版本，包含了有帮助的命令行警告 -->
<script src="../../plugins/vue/vue.js"></script>
<!-- 引入组件库 -->
<script src="../../plugins/element-ui/index.js"></script>
<!-- 引入axios -->
<script src="../../plugins/axios/axios.min.js"></script>
<script src="../../js/request.js"></script>
<script src="../../js/echarts.min.js"></script>
<script src="../../api/category.js"></script>
<script>
    const vm = new Vue({
        el: '#category-app',
        data() {
            return {
                action: '',
                counts: 0,
                page: 1,
                pageSize: 3,
                tableData: [],
                type: '',
                departmentNames: [],
                departmentCounts: [],
                drawData: [],
                classData: {
                    'dId': '',
                    'dName': '',
                    'detail': '',
                    'dialogVisible': false
                }
            }
        },
        computed: {},
        async created() {
            this.init()
            this.init2()
        },
        mounted() {
        },
        methods: {
            async init() {
                await getCategoryPage({'page': this.page, 'pageSize': this.pageSize}).then(res => {
                    if (String(res.code) === '1') {
                        this.tableData = res.data.list
                        this.counts = Number(res.data.total)
                        this.departmentCounts = []
                        this.departmentNames = []
                        for (let i = 0; i < res.data.list.length; i++) {
                            //处理结果集
                            this.departmentNames.push(res.data.list[i].dname)
                            this.departmentCounts.push(res.data.list[i].num);
                        }
                        //绘制柱状图
                        this.draw()
                    } else {
                        this.$message.error(res.msg || '操作失败')
                    }
                }).catch(err => {
                    this.$message.error('请求出错了：' + err)
                })
            },
            //请求下载excel表格
            exportExcel() {
                // getExcel().then(res => {
                //   this.$message.success('下载中……')
                // }).catch(err => {
                //   this.$message.error('下载请求出错了：' + err)
                // })
                this.$message.success('下载中，请确认下载！')
                const downloadUrl = 'http://localhost:8081/department/export';
                // 创建一个隐藏的iframe元素
                const iframe = document.createElement('iframe');
                iframe.style.display = 'none';
                document.body.appendChild(iframe);
                // 设置iframe的src属性，触发下载
                iframe.src = downloadUrl;
            },
            //上传文件成功的回调函数
            importSuccess(response, file, fileList) {
                if (response.code === 1) {//导入成功
                    this.$message.success('导入数据成功！')
                    //刷新数据
                    this.init()
                    this.init2()
                } else {//导入失败
                    let length = fileList.length;
                    //删除已上传文件列表最新的信息
                    fileList.splice(length - 1, 1)
                    this.$message.error('导入数据失败！请检查数据格式')
                }
            },
            //上传文件失败的回调函数
            importError() {
                this.$message.error('导入数据失败！请检查数据格式')
            },
            //获取数据且绘制饼状图
            async init2() {
                // 获取全部部门信息
                await getAll().then(res => {
                    let result = res.data.list
                    this.drawData = []
                    for (let i = 0; i < result.length; i++) {
                        //处理结果集
                        this.drawData.push({value: result[i].num, name: result[i].dname})
                    }
                    //绘制饼状图
                    this.draw2()
                }).catch(err => {
                    console.log("饼状图渲染失败！")
                })
            },
            //移除文件列表某个文件的确认弹窗
            beforeRemove(file, fileList) {
                return this.$confirm(`确定移除 ${file.name}？`);
            },
            handleQuery() {
                // this.page = 1;
                // vm.created();
                //初始化数据表和柱状图
                this.init()
                //初始化饼状图
                this.init2()
            },
            //渲染柱状图
            draw() {
                //  柱状图
                let dom = document.getElementById('container2');
                let myChart = echarts.init(dom, null, {
                    renderer: 'canvas',
                    useDirtyRect: false
                });
                let app = {};
                let option;
                option = {
                    xAxis: {
                        type: 'category',
                        data: this.departmentNames
                    },
                    yAxis: {
                        type: 'value'
                    },
                    series: [
                        {
                            data: this.departmentCounts,
                            type: 'bar'
                        }
                    ]
                };

                if (option && typeof option === 'object') {
                    myChart.setOption(option);
                }
                window.addEventListener('resize', myChart.resize);
            },
            //渲染饼状图
            draw2() {
                let dom = document.getElementById('container3');
                let myChart = echarts.init(dom, null, {
                    renderer: 'canvas',
                    useDirtyRect: false
                });
                let app = {};

                let option;

                option = {
                    legend: {
                        top: 'bottom'
                    },
                    toolbox: {
                        show: true,
                        feature: {
                            mark: {show: true},
                            dataView: {show: true, readOnly: false},
                            restore: {show: true},
                            saveAsImage: {show: true}
                        }
                    },
                    series: [
                        {
                            name: 'Nightingale Chart',
                            type: 'pie',
                            radius: [50, 250],
                            center: ['50%', '50%'],
                            roseType: 'area',
                            itemStyle: {
                                borderRadius: 8
                            },
                            data: this.drawData
                        }
                    ]
                };

                if (option && typeof option === 'object') {
                    myChart.setOption(option);
                }

                window.addEventListener('resize', myChart.resize);
            },
            // 添加
            addClass(st) {
                if (st == 'class') {
                    this.classData.title = '新增部门'
                    this.type = '1'
                } else {
                    this.classData.title = '新增套餐分类'
                    this.type = '2'
                }
                this.action = 'add'
                this.classData.dId = ''
                this.classData.dName = ''
                this.classData.detail = ''
                this.classData.dialogVisible = true
            },
            editHandle(data) {
                this.action = 'edit'
                this.classData.dId = data.did
                this.classData.dName = data.dname
                this.classData.detail = data.detail
                this.classData.dialogVisible = true
            },
            // 关闭弹窗
            handleClose(st) {
                this.classData.dialogVisible = false
            },
            //删除
            deleteHandle(row) {
                this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                    'confirmButtonText': '确定',
                    'cancelButtonText': '取消',
                    'type': 'warning'
                }).then(() => {
                    deleCategory(row.did).then(res => {
                        if (res.code === 1) {
                            this.$message.success('删除成功！')
                            this.handleQuery()
                        } else {
                            this.$message.error(res.msg || '操作失败')
                        }
                    }).catch(err => {
                        this.$message.error('请求出错了：' + err)
                    })
                })
            },
            //数据提交
            submitForm(st) {
                const classData = this.classData
                console.log(classData)
                // const valid = (classData.name === 0 ||classData.name)  && (classData.sort === 0 || classData.sort)
                if (this.action === 'add') {
                    addCategory(classData).then(res => {
                        if (res.code === 1) {
                            this.$message.success('部门添加成功！')
                            if (!st) {
                                this.classData.dialogVisible = false
                            } else {
                                this.classData.name = ''
                                this.classData.sort = ''
                            }
                            this.handleQuery()

                        } else {
                            this.$message.error(res.msg || '操作失败')
                        }
                    }).catch(err => {
                        this.$message.error('请求出错了：' + err)
                    })
                } else {
                    editCategory(classData).then(res => {
                        if (res.code === 1) {
                            this.$message.success('部门修改成功！')
                            this.handleQuery()
                            this.classData.dialogVisible = false
                        } else {
                            this.$message.error(res.msg || '操作失败')
                        }
                    }).catch(err => {
                        this.$message.error('请求出错了：' + err)
                    })
                }
            },
            handleSizeChange(val) {
                this.pageSize = val
                this.init()
            },
            handleCurrentChange(val) {
                this.page = val
                this.init()
            },
        }
    })
</script>
</body>
</html>